import store from "@/store/index.js";
// const { base64decode, base64encode } = require("nodejs-base64");
// import CryptoJS from "crypto-js";
// import md5 from "js-md5";

const titleMsg = "login..."

export default {
	post: (url, data = {}, header = {}) => {
		
		uni.showLoading({
			title: titleMsg,
			mask: true,
		});
		return new Promise((reslove, reject) => {
			uni.request({
				url,
				data,
				method: "POST",
				header: {
					...header,
					"TOKEN": store.state.TOKEN,
				},
				success: (result) => {
					reslove(result);
				},
				fail: (fail) => {
					reject(fail);
				},
				complete: (result) => {
					// 40000:重新登录
					// 0:正常返回
					// -1:报错，提示信息
					uni.hideLoading();
					if (result.data.code === -1) {
						uni.showToast({
							title: result.data.msg,
							icon: "none",
							duration: 3000,
						});
					} else if (result.data.code === 40000) {
						store.commit('setToken', '')
						store.commit('setUid', '')
						uni.reLaunch({
							url: '/pages/login/index'
						})
					}
				},
			});
		});
	},
	get: (url, data, header) => {
		return new Promise((reslove, reject) => {
			uni.request({
				url,
				data,
				method: "GET",
				header: {
					...header,
					"TOKEN": store.state.TOKEN,
				},
				success: (result) => {
					reslove(result);
				},
				fail: (fail) => {
					reject(fail);
				},
				complete: (result) => {
					// 40000:重新登录
					// 0:正常返回
					// -1:报错，提示信息
					uni.hideLoading();
					if (result.data.code === -1) {
						uni.showToast({
							title: result.data.msg,
							icon: "none",
							duration: 3000,
						});
					} else if (result.data.code === 40000) {
						store.commit('setToken', '')
						store.commit('setUid', '')
						uni.reLaunch({
							url: '/pages/login/index'
						})
					}
				},
			});
		});
	},
	upload: (url, filePath, header = {}) => {
		uni.showLoading({
			title: titleMsg,
			mask: true,
		});
		return new Promise((reslove, reject) => {
			uni.uploadFile({
				url,
				filePath,
				header: {
					...header,
					"TOKEN": store.state.TOKEN,
				},
				formData: {
					directory: "authorization",
				},
				name: "imgPath",
				success: (result) => {
					reslove(result);
				},
				fail: (fail) => {
					reject(fail);
				},
				complete: (result) => {
					uni.hideLoading();
				},
			});
		});
	},
};
